#include <iostream>
#include "TcpServer.hpp"
#include <string>
#include <cstring>
#include <memory>
#include <unistd.h>
#include "Calculate.hpp"
using namespace std;


// 处理报文的方法
string handler_request(string& inbufferstream, bool* error_code) {
    *error_code = true;
    CAL::Calculate g_calculate;
    unique_ptr<Protocol::Factory> fact = unique_ptr<Protocol::Factory>(new Protocol::Factory());
    shared_ptr<Protocol::Request> req = fact->BuildRequest(); 

    // 读取到一个报文
    // 2、判断读到的字节流是否包含一个完成的报文
    string message;
    string total_send_string;
    while (Protocol::Decode(inbufferstream, &message)) {
        cout << "message == " << message << endl;
        *error_code = true;
    
        // 已经能保证至少读到了一个完整的报文了，进行反序列化
        if (!req->DeSerialize(message)) {
            cout << "DeSerialize error……" << endl;
            *error_code = false;
            return string();
        }
        cout << "DeSerialize success……" << endl;

        shared_ptr<Protocol::Response> resp = g_calculate.Cal(req);
        // 序列化response
        string send_string;
        resp->Serialize(&send_string);
        // 添加报文
        total_send_string += Protocol::Encode(send_string);
    }
    // 发送
    return total_send_string;
}

int main(int argc, char* args[]) {
    if (argc != 2) {
        cout << "Usage:\n" << args[0] << "local_port\n" << endl;
        return 0;
    }
    uint16_t localport = stoi(args[1]);
    unique_ptr<TcpServer> tsp = unique_ptr<TcpServer>(new TcpServer(localport, handler_request));
    // TcpServer* tsp = new TcpServer(localport, handler_request);
    tsp->Loop();



    return 0;
}